package com.guigu.commons.filter;

import com.guigu.commons.utils.JwtUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.util.StringUtils;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @ClassName:TokenAuthenticationFilter
 * @Description:授权过滤器
 * @Author:longtao
 * @Date:2021/6/28
 * @Version:1.0
 */

public class TokenAuthenticationFilter extends BasicAuthenticationFilter {
    private Logger log=LoggerFactory.getLogger(TokenAuthenticationFilter.class);
    private JwtUtils jwtUtils;

    public TokenAuthenticationFilter(AuthenticationManager authenticationManager, JwtUtils jwtUtils) {
        super(authenticationManager);
        this.jwtUtils = jwtUtils;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        System.out.println("经过了TokenAuthenticationFilter中的doFilterInternal方法");
        String requestRemoteAddr = request.getRemoteAddr();
        log.info("访问路径为:{}",request.getRequestURI());
        System.out.println("requestRemoteAddr = " + requestRemoteAddr);
        //获取当前认证成功用户权限信息
        UsernamePasswordAuthenticationToken authenticationToken = getAuthentication(request);
        //如果 有权限信息,放到springSecurity上下文中
        if (authenticationToken != null) {
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        }
        chain.doFilter(request, response);
    }


    private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request) {
        System.out.println("经过了TokenAuthenticationFilter中的UsernamePasswordAuthenticationToken方法");
        String url = request.getRequestURI();

        //从头部信息获取token
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)) {
            System.out.println("是否为空!");
            return null;
        }
        //获取用户id
        String id = JwtUtils.getMemberIdByJwtToken(request);
        //根据用户id获取他所对应的权限列表ntinue;
        Collection<GrantedAuthority> authority = new ArrayList<>();
        authority.add(new SimpleGrantedAuthority("admin"));
        return new UsernamePasswordAuthenticationToken(id, token, authority);
    }
}
